package com.gjy.sql.regexp;

import org.junit.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gjy
 * @version 1.0
 * @since 2024-02-28 14:17:03
 */
public class SqlRegexpTest {

    @Test
    public void test1() {
        String sql = "dele select";
        System.out.println(checkSql(sql));
        if (isValidSQL(sql)) {
            System.out.println("Valid SQL");
        } else {
            System.out.println("Invalid SQL");
        }
    }

    public static boolean isValidSQL(String sql) {
        String regex = "(?i)^(?=.*\\bselect\\b)(?!.*\\bdelete\\b|\\btruncate\\b|\\bdrop\\b|\\bupdate\\b).*$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql);
        return matcher.matches();
    }

    private boolean checkSql(String sql) {
        Pattern PATTERN = Pattern.compile("(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(update|or|delete"
                + "|insert|trancate|char|substr|ascii|declare|exec|master|into|drop|execute)\\b|(\\*|;|\\+|%))");
        Matcher matcher = PATTERN.matcher(sql);
        if (matcher.find()) {
            return false;
        }
        return sql.matches("^(?i)(\\s*)(select)(\\s+)(((?!(insert|delete|update)).)+)$");
    }
}
